package sword_offer;

import java.util.Arrays;

/**
 * @author Synhard
 * @version 1.0
 * @Class sword_offer.Code6
 * @Description 输入某二叉树的前序遍历和中序遍历的结果，请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-03-12 20:34
 */
public class Code6 {
    public static void main(String[] args) {
        int[] preorder = new int[]{3,9,20,15,7};
        int[] inorder = new int[]{9,3,15,20,7};
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length == 0) {
            return null;
        }
        TreeNode head = new TreeNode(preorder[0]);// 创建根节点
        int index = getIndex(preorder, inorder);// 找到该层对应的根节点所在中序遍历中的下标
        head.left = buildTree(Arrays.copyOfRange(preorder, 1, index + 1), Arrays.copyOfRange(inorder, 0, index));
        head.right = buildTree(Arrays.copyOfRange(preorder, index + 1, preorder.length), Arrays.copyOfRange(inorder, index + 1, inorder.length));
        return head;
    }

    public static int getIndex(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++) {
            if (inorder[i] == preorder[0]) {
                return i;
            }
        }
        return 0;
    }
}
